from flask import render_template, request, url_for, redirect, flash
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user

from watchlist import app, db
from watchlist.models import User, Movie
from watchlist.forms import AddMovieForm, LoginForm, SettingForm, EditMovieForm
from flask_paginate import Pagination, get_page_parameter
from datetime import datetime


@app.route('/', methods=['GET', 'POST'])
def index():
    form = AddMovieForm()  # 获取
    if form.validate_on_submit():
        movie = Movie(title=form.title.data, year=form.year.data)
        db.session.add(movie)
        db.session.commit()
        flash('Item created')
        return redirect(url_for('index'))

    PER_PAGE = 15

    # 获取当前为第几页
    page = request.args.get(get_page_parameter(), type=int, default=1)
    # 定义每页显示多少项
    start = (page-1)*PER_PAGE
    end = start+PER_PAGE
    # 使用切片来显示每页显示多少项
    posts = Movie.query.slice(start, end)
    pagination = Pagination(bs_version=3, page=page, total=Movie.query.count())
    context = {
        "posts": posts,
        "pagination": pagination
    }
    movies = Movie.query.all()
    return render_template('index.html', **context, movies=movies, form=form, current_time=datetime.utcnow())


@app.route('/movie/edit/<int:movie_id>', methods=['GET', 'POST'])
@login_required
def edit(movie_id):
    movie = Movie.query.get_or_404(movie_id)
    form = EditMovieForm()
    if form.validate_on_submit():
        title = form.title.data
        year = form.year.data

        movie.title = title
        movie.year = year
        db.session.commit()
        flash('Item updated.')
        return redirect(url_for('index'))  # 重定向回主页
    return render_template('edit.html', movie=movie, form=form)  # 传入被编辑的电影记录


@app.route('/movie/delete/<int:movie_id>', methods=['POST'])
@login_required  # 登录保护, 未登录不能访问
def delete(movie_id):
    movie = Movie.query.get_or_404(movie_id)
    db.session.delete(movie)
    db.session.commit()
    flash('Item deleted')
    return redirect(url_for('index'))


@app.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        username = form.username.data
        password = form.password.data

        if not username or not password:
            flash('Invalid input.')
            return redirect(url_for('login'))
        user = User.query.first()
        # 验证用户名和密码是否一致
        if username == user.username and user.validate_password(password):
            login_user(user)  # 登入用户
            flash('Login Success')
            return redirect(url_for('index'))

        flash('Invalid username or password.')
        return redirect(url_for('index'))
    return render_template('login.html', form=form)


@app.route('/logout')
@login_required
def logout():
    logout_user()  # 登出用户
    flash('Goodbye...')
    return redirect(url_for('index'))


@app.route('/setting', methods=['GET', 'POST'])
@login_required
def setting():
    form = SettingForm()
    if form.validate_on_submit():
        name = form.name.data
        current_user.name = name
        db.session.commit()
        flash('Setting updated.')
        return redirect(url_for('index'))
    return render_template('setting.html', form=form)

